Refactor OmniAuth configuration and fix it with 37Signals.

Akinori MUSHA 10 years ago
parent
commit
9defc7afb8
2 changed files with 29 additions and 17 deletions
  1. 1 1
      app/views/services/index.html.erb
  2. 28 16
      config/initializers/omniauth.rb

+ 1 - 1
app/views/services/index.html.erb

@@ -14,7 +14,7 @@
14 14
       <% if has_oauth_configuration_for?('twitter') %>
15 15
         <p><%= link_to "Authenticate with Twitter", "/auth/twitter" %></p>
16 16
       <% end %>
17
-      <% if has_oauth_configuration_for?('thirty_seven_signals') %>
17
+      <% if has_oauth_configuration_for?('37signals') %>
18 18
         <p><%= link_to "Authenticate with 37Signals (Basecamp)", "/auth/37signals" %></p>
19 19
       <% end -%>
20 20
       <% if has_oauth_configuration_for?('github') %>

+ 28 - 16
config/initializers/omniauth.rb

@@ -1,23 +1,35 @@
1
-LOADED_OMNIAUTH_STRATEGIES = {
2
-  'twitter'   => defined?(OmniAuth::Strategies::Twitter),
3
-  '37signals' => defined?(OmniAuth::Strategies::ThirtySevenSignals),
4
-  'github'    => defined?(OmniAuth::Strategies::GitHub)
1
+OMNIAUTH_PROVIDERS = {}.tap { |providers|
2
+  if defined?(OmniAuth::Strategies::Twitter) &&
3
+     (key = ENV["TWITTER_OAUTH_KEY"]).present? &&
4
+     (secret = ENV["TWITTER_OAUTH_SECRET"]).present?
5
+    providers['twitter'] = {
6
+      omniauth_params: [key, secret, authorize_params: {force_login: 'true', use_authorize: 'true'}]
7
+    }
8
+  end
9
+
10
+  if defined?(OmniAuth::Strategies::ThirtySevenSignals) &&
11
+     (key = ENV["THIRTY_SEVEN_SIGNALS_OAUTH_KEY"]).present? &&
12
+     (secret = ENV["THIRTY_SEVEN_SIGNALS_OAUTH_SECRET"]).present?
13
+    providers['37signals'] = {
14
+      omniauth_params: [key, secret]
15
+    }
16
+  end
17
+
18
+  if defined?(OmniAuth::Strategies::GitHub) &&
19
+     (key = ENV["GITHUB_OAUTH_KEY"]).present? &&
20
+     (secret = ENV["GITHUB_OAUTH_SECRET"]).present?
21
+    providers['github'] = {
22
+      omniauth_params: [key, secret]
23
+    }
24
+  end
5 25
 }
6 26
 
7 27
 def has_oauth_configuration_for?(provider)
8
-  LOADED_OMNIAUTH_STRATEGIES[provider.to_s] && ENV["#{provider.upcase}_OAUTH_KEY"].present? && ENV["#{provider.upcase}_OAUTH_SECRET"].present?
28
+  OMNIAUTH_PROVIDERS.key?(provider.to_s)
9 29
 end
10 30
 
11 31
 Rails.application.config.middleware.use OmniAuth::Builder do
12
-  if has_oauth_configuration_for?('twitter')
13
-    provider 'twitter', ENV['TWITTER_OAUTH_KEY'], ENV['TWITTER_OAUTH_SECRET'], authorize_params: {force_login: 'true', use_authorize: 'true'}
14
-  end
15
-
16
-  if has_oauth_configuration_for?('37signals')
17
-    provider '37signals', ENV['THIRTY_SEVEN_SIGNALS_OAUTH_KEY'], ENV['THIRTY_SEVEN_SIGNALS_OAUTH_SECRET']
18
-  end
19
-
20
-  if has_oauth_configuration_for?('github')
21
-    provider 'github', ENV['GITHUB_OAUTH_KEY'], ENV['GITHUB_OAUTH_SECRET']
22
-  end
32
+  OMNIAUTH_PROVIDERS.each { |name, config|
33
+    provider name, *config[:omniauth_params]
34
+  }
23 35
 end